import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('qtagg')
from scipy.io import wavfile

# 读取音频文件
Fs, audio = wavfile.read('example.wav')  # 读取音频文件

# 如果是立体声，转换为单声道
if len(audio.shape) > 1:
    audio = np.mean(audio, axis=1)
    
N = len(audio)  # 采样点数

# 进行 FFT 计算
Y = np.fft.fft(audio)  # 计算FFT
Y = np.abs(Y[:N//2])   # 取前一半有效频率分量并计算幅值
f = np.arange(0, N//2) * (Fs / N)  # 计算频率轴

# 找到主要特征频率
peakIndex = np.argmax(Y)  # 寻找最大幅值的索引
featureFrequency = f[peakIndex]

# 绘制频谱
plt.figure()
plt.plot(f, Y)
plt.xlabel('Frequency (Hz)')
plt.ylabel('Amplitude')
plt.title('Frequency Spectrum of Audio')
plt.grid(True)
plt.show()

# 显示特征频率
print(f'The dominant frequency is: {featureFrequency:.2f} Hz')
